<template>
  <div class="login-wrapper">
    <div class="login-wrapper-inner">
      <div class="login-wrapper-title">
        {{ t("login.title") }}
      </div>
      <el-form :disabled="isLoginPending">
        <el-form-item :label="t('login.username')">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item :label="t('login.password')">
          <el-input v-model="user.password" type="password" />
        </el-form-item>
        <el-button
          type="primary"
          :loading="isLoginPending"
          :disabled="isLoginPending"
          @click="submit"
        >
          {{ t("login.submit") }}
        </el-button>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts">
import { definePageMeta } from "#imports";

definePageMeta({
  layout: "narrow"
});
</script>
<script lang="ts" setup>
import {
  doLogin,
  reactive,
  useGlobalCookie,
  useRouter,
  useI18n,
  useUser
} from "#imports";
import { ElMessage } from "element-plus";

const router = useRouter();
const { t } = useI18n();
const user = reactive({
  username: "",
  password: ""
});
const { execute, error, data, pending: isLoginPending } = doLogin(user);
const { refresh: refreshUser } = useUser();
const accessToken = useGlobalCookie("access_token", {
  maxAge: 30 * 86400
});

const submit = () => {
  execute().then(() => {
    if (!error.value && data.value) {
      accessToken.value = data.value.accessToken;
      refreshUser().then(() => {
        ElMessage.success(t("login.login-success"));
        router.push("/");
      });
    } else {
      ElMessage.error(error.value?.Message || t("login.login-failed"));
    }
  });
};
</script>
<style lang="scss" scoped>
.login-wrapper {
  background: var(--color-white);
  margin-top: 36px;
  border-radius: var(--border-radius);
  padding: 36px 16px 72px;
  box-sizing: border-box;

  &-inner {
    margin: 0 auto;
    max-width: 320px;
  }

  &-title {
    font-size: 24px;
    font-weight: 500;
    margin-bottom: 24px;
    text-align: center;
  }
}
</style>
